package com.explorx.sns.puma.im.core.controller;

import com.explorex.puma.common.login.LoginUser;
import com.explorex.puma.common.login.TokenService;
import com.explorex.puma.common.login.User;
import com.explorex.puma.common.login.UserContextHolder;
import com.explorex.puma.common.web.HttpResult;
import com.explorx.sns.puma.im.core.chat.UserInfoDomainService;
import com.explorx.sns.puma.im.core.chat.UserRelationService;
import com.explorx.sns.puma.im.core.chat.consts.Constants;
import com.explorx.sns.puma.im.core.chat.model.*;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserInfoController {
    @Value("${token.header:Authorization}")
    private String header;

    @Resource
    private UserInfoDomainService userInfoDomainService;

    @Resource
    private UserRelationService userRelationService;

    @Resource
    private TokenService tokenService;


    @PostMapping("/get")
    public HttpResult getUsersInfo(@RequestBody List<Long> uids){
        final List<UserInfoModel> usersInfo = userInfoDomainService.getUsersInfo(uids);
        return HttpResult.success(usersInfo);
    }


    /**
     * /api/user/v1/my/profile/query
     * @param
     * @return
     */
    @GetMapping("/v1/my/profile/query")
    public HttpResult getUserProfile(@RequestParam Long userId){
        try {
            Preconditions.checkArgument(!Objects.isNull(userId),"userId 不能为空");
            final UserInfoModel userInfo = userInfoDomainService.getUserInfo(userId);
            final Pair<Integer, Integer> followAndFansCnt = userRelationService.queryFollowAndFansCnt(userId);
            userInfo.setFansCnt(followAndFansCnt.getValue());
            userInfo.setFollowCnt(followAndFansCnt.getKey());
            return   HttpResult.success(userInfo);
        }catch (IllegalArgumentException e){
            return HttpResult.fail(-1,e.getMessage());
        } catch (Exception e){
            log.error("userId profile get exception userId={}",userId,e);
        }
        return HttpResult.fail(-1,"服务异常");
    }

    @PostMapping("/login")
    public HttpResult login(@RequestBody LoginReq req, HttpServletResponse httpServletResponse){
        final UserInfoModel userInfoModel = userInfoDomainService.userLogin(req.getPhone(), req.getPassword());

        if(userInfoModel!=null){
            addCookies(userInfoModel,httpServletResponse);
        }
        return   HttpResult.success(userInfoModel);
    }

    private void addCookies(UserInfoModel userInfoModel, HttpServletResponse httpServletResponse){
        LoginUser currentUsr=LoginUser.builder()
                .user(new User(userInfoModel.getUserId(),userInfoModel.getUserName(),System.currentTimeMillis()))
                .userName(userInfoModel.getUserName()).build();
        final String token = tokenService.createToken(currentUsr);
        httpServletResponse.addHeader(header,token);
        Cookie tokenCookie=new Cookie("token", Constants.TOKEN_PREFIX+token);
        tokenCookie.setPath("/api");
        httpServletResponse.addCookie(tokenCookie);
    }

    @PostMapping("/v1/my/profile/edit/name")
    public HttpResult editName(@RequestBody String userName){
        final LoginUser userInfo = UserContextHolder.getUserInfo();
        userInfoDomainService.editName(userInfo.getUser().getUid(),userName);
        return   HttpResult.success();
    }

    @PostMapping("/v1/my/profile/edit/birthday")
    public HttpResult editBirthDay(@RequestBody String birthDay){
        final LoginUser userInfo = UserContextHolder.getUserInfo();
        userInfoDomainService.editBirthDay(userInfo.getUser().getUid(),birthDay);
        return   HttpResult.success();
    }


    @PostMapping("/v1/my/profile/edit/gender")
    public HttpResult editGender(@RequestBody int gender){
        final LoginUser userInfo = UserContextHolder.getUserInfo();
        userInfoDomainService.editGender(userInfo.getUser().getUid(),gender);
        return   HttpResult.success();
    }


    @PostMapping("/v1/my/profile/edit/school")
    public HttpResult editEducation(@RequestBody String education){
        final LoginUser userInfo = UserContextHolder.getUserInfo();
        userInfoDomainService.editEducation(userInfo.getUser().getUid(),education);

        return   HttpResult.success();
    }

    @PostMapping("/v1/my/profile/edit/age")
    public HttpResult editAge(@RequestBody int age){
        final LoginUser userInfo = UserContextHolder.getUserInfo();
        userInfoDomainService.editAge(userInfo.getUser().getUid(),age);
        return   HttpResult.success();
    }

    @PostMapping("/v1/my/profile/edit/city")
    public HttpResult editCity(@RequestBody int cityCode){
        final LoginUser userInfo = UserContextHolder.getUserInfo();
        userInfoDomainService.editCity(userInfo.getUser().getUid(),cityCode);
        return   HttpResult.success();
    }


    @PostMapping("/v1/my/profile/edit/avatar")
    public HttpResult editAvatar(@RequestBody String avatar){
        final LoginUser userInfo = UserContextHolder.getUserInfo();
        userInfoDomainService.editAvatar(userInfo.getUser().getUid(),avatar);
        return   HttpResult.success();
    }
}
